package com.fitzone.web.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.time.LocalDateTime;

/**
 * 元数据处理器
 * 插入和更新时自动填充
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("insert填充");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        metaObject.setValue("isDeleted", 0);
        metaObject.setValue("createTime", new Timestamp(System.currentTimeMillis()));
        metaObject.setValue("updateTime", new Timestamp(System.currentTimeMillis()));
        if (authentication == null || "anonymousUser".equals(authentication.getPrincipal())) {
            metaObject.setValue("createBy", 0L);
            metaObject.setValue("updateBy", 0L);
        } else {
            metaObject.setValue("createBy", authentication.getPrincipal());
            metaObject.setValue("updateBy", authentication.getPrincipal());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("update填充");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        metaObject.setValue("updateTime", new Timestamp(System.currentTimeMillis()));
        if (authentication == null){
            metaObject.setValue("updateBy", 0L);
        }else {
            metaObject.setValue("updateBy", authentication.getPrincipal());
        }
    }
}
